﻿#include <QJsonArray>
#include "CDevDataCam.h"
#include <QDebug>

CDevDataCam::CDevDataCam()
{
	m_pMutex = new QMutex();
	m_sDevGuid = "";					   //归属设备Guid
	m_bInit = false;                       //云台设备是否已经初始化
	m_bLogin = false;                      //云台设备是否连接
	m_bLoginValue = true;					
	m_sCamerName = "";					   //云台名称
	m_sServerIp = "";					   //归属算法服务器Ip地址
	m_sCamerIp = "";                       //云台ip
	m_nCamerPort = 0;                      //云台端口号
	m_nChannel = 1;						   //摄像头在Ai服务器中的通道号
	m_nChannelHW = 2;						   //摄像头在Ai服务器中的通道号
	m_sUserName = "";                      //用户名
	m_sPassWord = "";                      //密码
	m_sRecordPath = "";					   //手动录像拍照保存的路径
	m_sRtspUrlImg = "";
	m_sRtspUrlIr = "";
	m_nVideoType = 0;
	m_bCoalFlow=true;						//煤流量
	m_bBeltForeign = true;					//皮带异物
	m_bLargeCoal = true;						//大块煤
	m_bBeltDeviation = true;					//皮带跑偏
	m_bSafetyHelmet = true;					//安全帽反光衣
	m_bSmokeFire = true;						//烟雾火点
	m_bSmokeMakeCall = true;					//抽烟打电话
	m_bTemp = true;							//测温报警
	m_bPerimeter = true;							//周界防范
	m_bBlock = true;							//堵料识别
	m_bThrow = true;							//抛洒滴漏
	m_bStreet = true;							//街面行为
	m_bBeltRun = false;							//皮带启停信号

	m_dLastCoalFlow = QDateTime::currentDateTime().addDays(-1);						//煤流量
	m_dLastBeltForeign = QDateTime::currentDateTime().addDays(-1);					//皮带异物
	m_dLastLargeCoal = QDateTime::currentDateTime().addDays(-1);						//大块煤
	m_dLastBeltDeviation = QDateTime::currentDateTime().addDays(-1);					//皮带跑偏
	m_dLastSafetyHelmet = QDateTime::currentDateTime().addDays(-1);			//安全帽反光衣
	m_dLastSmokeFire = QDateTime::currentDateTime().addDays(-1);						//烟雾火点
	m_dLastSmokeMakeCall = QDateTime::currentDateTime().addDays(-1);				//抽烟打电话
	m_dLastTemp = QDateTime::currentDateTime().addDays(-1);			//测温报警
	m_dLastPerimeter = QDateTime::currentDateTime().addDays(-1);			//周界防范
	m_dLastBlock = QDateTime::currentDateTime().addDays(-1);			//堵料
	m_dLastThrow = QDateTime::currentDateTime().addDays(-1);			//抛洒滴漏
	m_dLastStreet = QDateTime::currentDateTime().addDays(-1);			//街面行为
	m_dBeltRun = QDateTime::currentDateTime().addDays(-1);//皮带启停信号
	m_vecAlarm.clear();
}

CDevDataCam::~CDevDataCam()
{
	
}

AlarmData AlarmData::fromJson(const QJsonObject &json)
{
	AlarmData data;
	if (json.contains("dateTime"))
	{
		data.dateTime = QDateTime::fromString(json["dateTime"].toString(), "yyyy-MM-ddThh:mm:ss+08:00");
	}
	else
	{
		data.dateTime = QDateTime::currentDateTime();
	}
	if (json.contains("ipAddress"))
	{
		data.ipAddress = json["ipAddress"].toString();
	}
	if (json.contains("portNo"))
	{
		data.portNo = json["portNo"].toInt();
	}
	if (json.contains("eventState"))
	{
		data.eventState = json["eventState"].toString();
	}
	if (json.contains("eventType"))
	{
		data.eventType = json["eventType"].toString();
	}
	if (json.contains("eventDescription"))
	{
		data.eventDescription = json["eventDescription"].toString();
	}
	if (json.contains("MPID"))
	{
		data.MPID = json["MPID"].toString();
	}
	if (json.contains("MPName"))
	{
		data.MPName = json["MPName"].toString();
	}
	if (json.contains("channelID"))
	{
		data.channelID = json["channelID"].toInt();
	}
	if (json.contains("url"))
	{
		data.url = json["url"].toString();
	}
	// 初始化规则名为空
	data.sRuleName = "";

	// 解析AIOP数据
	if (json.contains("AIOPData"))
	{
		QJsonObject aiopJson = json["AIOPData"].toObject();
		if (aiopJson.contains("events"))
		{
			// 解析事件信息
			QJsonObject eventsObj = aiopJson["events"].toObject();
			if (eventsObj.contains("alertInfo"))
			{
				QJsonArray alertInfoArray = eventsObj["alertInfo"].toArray();
				for (const QJsonValue &alertValue : alertInfoArray)
				{
					QJsonObject alertObj = alertValue.toObject();
					data.aiopData.events.alertInfo.append(alertObj);

					// 解析规则名
					if (alertObj.contains("ruleInfo"))
					{
						QJsonObject ruleInfoObj = alertObj["ruleInfo"].toObject();
						if (ruleInfoObj.contains("ruleName"))
						{
							data.sRuleName = ruleInfoObj["ruleName"].toString();
						}
					}
				}
			}
		}
	}
	return data;
}

AlarmData AlarmData::fromKYJson(const QJsonObject &json)
{
	AlarmData data;
	if (json.contains("timestamp"))
	{
		data.dateTime = QDateTime::fromString(json["timestamp"].toString(), "yyyy-MM-dd hh:mm:ss");
	}
	if (json.contains("algorithm_id"))
	{
		data.eventType = QString::number(json["algorithm_id"].toInt());
	}
	if (json.contains("alarm_pic_url"))
	{
		data.url = json["alarm_pic_url"].toString();
	}
	if (json.contains("degree"))
	{
		data.degree = json["degree"].toInt();
	}
	if (json.contains("camera_id"))
	{
		data.channelID = json["camera_id"].toInt();
	}
	if (json.contains("online_status"))
	{
		data.eventState = json["online_status"].toString();
	}
	return data;
}

AlarmData AlarmData::fromXml(QString sXml)
{
	AlarmData alarm;
	// 1. 前置检查：XML是否为空或无效
	if (sXml.trimmed().isEmpty())
	{
		qWarning() << "XML string is empty";
		alarm.bIsValid = false;
		return alarm;
	}

	// 2. 检查基本的XML结构
	if (!sXml.contains("<?xml")) 
	{
		qWarning() << "Invalid XML structure: missing XML declaration or root element";
		alarm.bIsValid = false;
		return alarm;
	}
	QXmlStreamReader xml(sXml);
	QString currentElement;
	int elementCount = 0;
	const int MAX_ELEMENTS = 1000; // 防止恶意XML攻击
	while (!xml.atEnd() && !xml.hasError())
	{
		const QXmlStreamReader::TokenType token = xml.readNext();
		elementCount++;
		switch (token)
		{
		case QXmlStreamReader::StartElement:
			currentElement = xml.name().toString();

			if (currentElement == "ipAddress")
			{
				alarm.ipAddress = xml.readElementText();
			}
			else if (currentElement == "portNo")
			{
				alarm.portNo = xml.readElementText().toInt();
			}
			else if (currentElement == "dynChannelID")
			{
				// 优先使用dynChannelID
				alarm.channelID = xml.readElementText().toInt();
			}
			else if (currentElement == "channelID") 
			{
				// 如果没有dynChannelID，使用channelID
				if (alarm.channelID == 0)
				{
					alarm.channelID = xml.readElementText().toInt();
				}
			}
			else if (currentElement == "dateTime")
			{
				QString dateTimeStr = xml.readElementText();
				alarm.dateTime = QDateTime::fromString(dateTimeStr, "yyyy-MM-ddThh:mm:ss+08:00");
			}
			else if (currentElement == "eventType")
			{
				alarm.eventType = xml.readElementText();
			}
			else if (currentElement == "eventState") 
			{
				alarm.eventState = xml.readElementText();
			}
			else if (currentElement == "eventDescription")
			{
				alarm.eventDescription = xml.readElementText();
			}
			else if (currentElement == "thermalURL") 
			{
				alarm.url = xml.readElementText();
			}
			else if (currentElement == "visibleLightURL") 
			{
				// 如果没有热成像URL，使用可见光URL
				if (alarm.url.isEmpty()) {
					alarm.url = xml.readElementText();
				}
			}
			else if (currentElement == "bkgUrl")
			{
				// 如果没有热成像URL，使用可见光URL
				if (alarm.url.isEmpty()) {
					alarm.url = xml.readElementText();
				}
			}
			else if (currentElement == "channelName") 
			{
				// 可以存储通道名称
				QString channelName = xml.readElementText();
			}
			break;

		default:
			break;
		}
		if (elementCount  > MAX_ELEMENTS)
		{
			alarm.bIsValid = false;
			break;
		}
	}
	return alarm;
}